<template>
    <view class="globe_back">
        <view class="box">
            <u-picker :show="show" :columns="columns" keyName="title" @confirm="confirm" @cancel="cancel"></u-picker>
            <view class="flex justify_content_between back_fff model" @click="show = true">
                <view class="flex carbox1">
                    <text class="carmodel">车型</text>
                    <input style="font-size: 28rpx" disabled placeholder="请选择故障车型" v-model="title" />
                </view>
                <view><image class="icon_r" :src="url + 'next-icon.png'" mode="widthFix"></image></view>
            </view>
            <!-- 现场照片 -->
            <view class="imgbox">
                <text class="manageLabel mt-20 mr-10">现场照片</text>
                <view>
                    <!-- <view class="xcimg" v-if="formData.images.length > 0" v-for="(item, i) in formData.images">
                        <image class="storeImg" :src="$lz.cdn(item, 3)" mode="center" style="width: 140rpx; height: 140rpx; display: inline-block"></image>
                        <view class="imm_delete" @click="deletephotos(i)">
                            <image class="icon_ljt" :src="url + 'icon_sc.png'"></image>
                        </view>
                    </view>
                    <view class="img_add" style="display: inline-block" v-if="formData.images.length < maxImagesNum" @click="instoreImages">
                        <image :src="url + 'updata-img.png'" mode="widthFix" style="width: 100%; height: 100%"></image>
                    </view> -->
					<u-upload
						:fileList="fileList6"
						@afterRead="afterRead"
						@delete="deletePic"
						name="6"
						multiple
						:maxCount="6"
						width="70"
						height="70"
						>
						<view class="img_add" style="display: inline-block" v-if="formData.images.length < maxImagesNum" @click="instoreImages">
						    <image :src="url + 'updata-img.png'" mode="widthFix" style="width: 100%; height: 100%"></image>
						</view>
					</u-upload>
                </view>
            </view>
            <view class="model back_fff">
                <!-- 车辆位置 -->
                <view class="flex justify_content_between">
                    <view class="flex carbox1">
                        <view class="carmodel">车辆位置</view>
                        <view class="flex justify_content_between line_F7FAFF from-title-box align_items_center" style="width: 80%" @click="handleChooseFromAddress">
                            <input
                                class="f_28 cl_00091A pb_16"
                                disabled
                                placeholder-class="cl_CCCED1"
                                v-model="trailer_address"
                                type="text"
                                value=""
                                placeholder="请选择故障车辆位置"
                            />
                            <image class="img_32" :src="url + 'posi-icon.png'" mode="widthFix"></image>
                        </view>
                    </view>
                </view>
                <!-- 目的地 -->
                <view class="flex justify_content_between back_fff">
                    <view class="flex carbox">
                        <view class="carmodel">目的地</view>
                        <view class="flex justify_content_between line_F7FAFF from-title-box align_items_center" style="width: 80%" @click="handleChooseToAddress">
                            <input
                                class="f_28 cl_00091A pb_16"
                                disabled
                                placeholder-class="cl_CCCED1"
                                v-model="user_location"
                                type="text"
                                value=""
                                placeholder="请选择拖车目的地"
                            />
                            <image class="img_32" :src="url + 'posi-icon.png'" mode="widthFix"></image>
                        </view>
                    </view>
                </view>
                <!-- 姓名 -->
                <view class="flex namebox carbox">
                    <text class="nametitle">姓名</text>
                    <view class="inpu line_F7FAFF">
                        <input v-model="formData.name" class="name" type="text" placeholder="请填写您的姓名" />
                    </view>
                </view>
                <!-- 联系电话 -->
                <view class="flex namebox carbox">
                    <text class="nametitle">联系电话</text>
                    <view class="inpu line_F7FAFF">
                        <input v-model="formData.mobile" class="name" type="text" placeholder="请填写您的联系电话" />
                    </view>
                </view>
                <!-- 优惠券 -->
                <view class="flex justify_content_between back_fff">
                    <view class="flex carbox">
                        <view class="carmodel">优惠券</view>
                        <view class="flex justify_content_between line_F7FAFF from-title-box align_items_center" style="width: 80%" @click="yhq()">
                            <input class="f_28 cl_00091A pb_16" disabled placeholder-class="cl_CCCED1" type="text" value="" v-model="coupon_title" placeholder="请选择优惠券" />
                            <image class="img_32" :src="url + 'next-icon.png'" mode="widthFix"></image>
                        </view>
                    </view>
                </view>
            </view>
            <view class="tip" v-if="title">请确认信息准确性，{{title}}拖车订单每需{{unitPrice}}元</view>
        </view>
        <!-- 底部 -->
        <view class="button flex justify_content_between">
            <view class="TotalPrice">
                <view class="f_24">
                    合计：
                    <text style="color: #ff6401; font-size: 32rpx; font-weight: bold">{{actual_price}}</text>
                </view>
                <view class="cl_999CA3 f_24 mt_16">
                    距离约
                    <text class="cl_00091A mr_24">{{ k }}</text>
                    优惠
                    <text class="cl_00091A">{{ coupon_price }}</text>
                </view>
            </view>
            <view class="buy" @click="tj">立即下单</view>
        </view>
        <!-- 优惠券弹窗 -->
        <u-popup :show="couponShow" :round="10" mode="bottom" @close="close" @open="open">
            <view>
                <u-radio-group v-model="radiovalue13" placement="column" @change="groupChanges" iconPlacement="right">
					<scroll-view class="scroll-view_H" scroll-y="true" @scroll="scroll" style="height: 500rpx;">
                    <u-radio
                        :customStyle="{
                            margin: '8px 16px',
                            background: '#FFEFE5',
                            padding: '16px'
                        }"
                        v-for="(item, index) in coupon"
                        :key="index"
                        :label="index"
                        :name="index"
                        @change="radioChange"
                    >
                        <view class="flex couponBox">
                            <view class="discount">
                                <view style="font-size: 52rpx">{{ item.coupon_price }}</view>
                                <view>{{ item.coupon_text }}</view>
                            </view>
                            <view class="title">
                                <view>{{ item.coupon_title }}</view>
                                <view class="time">有效期至{{ item.useageend_time }}</view>
                            </view>
                        </view>
                    </u-radio>
					</scroll-view>
                    <view class="couponBtn" @click="submit">确认</view>
                </u-radio-group>
            </view>
        </u-popup>
    </view>
</template>

<script>
import { getConfByCode, upload, getDictByCode, unifyOrder, getDirectionByDriving } from '@/api';

export default {
    data() {
        return {
            carMode: {},
            show: false,
            couponShow: false,
            url: '',
            unitPrice: 0,
            maxImagesNum: 8,
            Coupon: '',
			fileList6: [], 
            formData: {
                type: 0,
                images: [],
                fromAddress: {
                    address: '',
                    fullAddress: '',
                    latitude: '',
                    longitude: '',
                    name: ''
                },
                toAddress: {
                    address: '',
                    fullAddress: '',
                    latitude: '',
                    longitude: '',
                    name: ''
                },
                name: '',
                mobile: '',
                distance: 0,
                discount: 0
            },
            columns: [],
            // 优惠券
            coupon: [
                // {
                //   name: "新人优惠券",
                //   time: "2023-12-15",
                //   title: "7折",
                //   threshold: "无使用门槛",
                //   disabled: false,
                // },
                // {
                //   name: "会员券",
                //   time: "2023-12-25",
                //   title: "8折",
                //   threshold: "无使用门槛",
                //   disabled: false,
                // },
            ],
			trailer_address:'',
			trailer_longitude:'',
			trailer_latitude:'',
			user_location:'',
			user_longitude:'',
			user_latitude:'',
			title:'',
			lat:'',
			lng:'',
			images:[],
			k:0,
			// coupon_price:0,
			order_price:0,
			actual_price:0,
			radiovalue13:-1,
			coupon_price:0,
			coupon_title:'',
			coupon_id:0,
			coupon:[],
        };
    },
    onShow() {
		var that= this
		uni.getLocation({
			type: 'wgs84',
			success: function (res) {
				that.lat=res.latitude;
				that.lng=res.longitude;
			}
		});
        this.getUnitPrice();
        // this.getCarMode();
        this.url = this.baseUrl + this.imgPath;
    },
    watch: {
        'formData.fromAddress': {
            handler: function ({ latitude: fromLatitude, longitude: fromLongitude }) {
                const { latitude: toLatitude, longitude: toLongitude } = this.formData.toAddress;
                if (fromLatitude && fromLongitude && toLatitude && toLongitude) {
                    const from = `${fromLatitude},${fromLongitude}`;
                    const to = `${toLatitude},${toLongitude}`;
                    this.getDistance({ from, to });
                }
            },
            deep: true,
            immediate: true
        },
        'formData.toAddress': {
            handler: function ({ latitude: toLatitude, longitude: toLongitude }) {
                const { latitude: fromLatitude, longitude: fromLongitude } = this.formData.fromAddress;
                if (fromLatitude && fromLongitude && toLatitude && toLongitude) {
                    const from = `${fromLatitude},${fromLongitude}`;
                    const to = `${toLatitude},${toLongitude}`;
                    this.getDistance({ from, to });
                }
            },
            deep: true,
            immediate: true
        }
    },
    methods: {
        getUnitPrice() {
			this.$.ajax(1,"POST","index/list_of_vehicle_models",{},(res)=>{
			  if(res.code==200){
				
				 this.columns = [res.data];
			  }else{
			     this.$.ti_shi(res.msg);
			  }
			})

        },
        // getCarMode() {
        //     getDictByCode('car_mode').then((res) => {
        //         // this.carMode = res.data[0];
        //         // this.formData.type = this.carMode.key;
        //         this.columns = [res.data];
        //     });
        // },
        getDistance(args) {
            getDirectionByDriving(args).then((res) => {
                const { distance, duration } = res.data;
                this.formData.distance = distance;
                console.log('res', distance, duration);
            });
        },
        handleUnifyOrder(args) {
            unifyOrder(4, args).then((res) => {
                console.log('res', res);
            });
        },
        submit() {
            this.couponShow = false;
        },
        groupChange(n) {
            console.log('groupChange', n);
            this.Coupon = n;
        },
        radioChange(n) {
            console.log('radioChange', n);
        },
        confirm(e) {
            console.log(e.value[0]);
            this.title = e.value[0].title;
            this.formData.type = e.value[0].key;
			this.unitPrice = e.value[0].money;
			this.actual_price=e.value[0].money;
            this.show = false;
        },
        cancel() {
            this.show = false;
        },
        // 删除现场照片
        deletephotos(i) {
            this.formData.images.splice(i, 1);
        },
        // 拖车下单
        tj() {
			
			if(!this.title){
				this.$.ti_shi('请选择故障车型');
				return;
			}
			if(!this.images.join(',')){
				this.$.ti_shi('请上传现场图片');
				return;
			}
			if(!this.trailer_address){
				this.$.ti_shi('请选择车辆位置');
				return;
			}
			if(!this.user_location){
				this.$.ti_shi('请选择目的地');
				return;
			}
			if(!this.formData.name){
				this.$.ti_shi('请填写姓名');
				return;
			}
			if(!this.formData.mobile){
				this.$.ti_shi('请填写联系电话');
				return;
			}
			
          this.$.ajax(1,"POST","index/trailer_ordering",{
				defective_vehicle_model:this.title,	
				on_site_photos:this.images.join(','),	
				trailer_address:this.trailer_address,	
				trailer_longitude:this.trailer_longitude,	
				trailer_latitude:this.trailer_latitude,	
				user_location:this.user_location,	
				user_longitude:this.user_longitude,	
				user_latitude:this.user_latitude,	
				consignee:this.formData.name,	
				mobile:this.formData.mobile,	
				// usercoupon_id:0,	
				coupon_price:this.coupon_price,
				coupon_id:this.coupon_id,
				// coupon_price:this.coupon_price,
				order_price:this.order_price,
				actual_price:this.actual_price,
				t_km:this.k,
				
		  },(res)=>{
			  
				if(res.code==200){
					var that =this
				     uni.requestPayment({
				     	provider: "weixin",
				     	timeStamp: res.data.timeStamp,
				     	nonceStr: res.data.nonceStr,
				     	package: res.data.package,
				     	signType: res.data.signType,
				     	paySign: res.data.paySign,
				     	success: function (ress) {
				     		setTimeout(() => {
				     			uni.navigateBack({
				     				delta:1
				     			})
				     		}, 1000);
				     	},
				     	fail: function (err) {
				     		console.log(err)
				     		that.$.ti_shi(err)
				     					
				     	}
				     });
				}else{
				   this.$.ti_shi(res.msg);
				}
          })
        },
		yhq(){
			this.$.ajax(1,"POST","index/money_coupon_list",{
				money:this.order_price,
			},(res)=>{
			  if(res.code==200){
				    	console.log(res.data)
						if(res.data.length>0){
							this.coupon=res.data;
							// this.radiovalue13=res.data[0].id
							// this.xz_coupon=res.data[0];
							this.show=true
							this.couponShow=true
							
						}else{
							this.$.ti_shi('暂无可用优惠券');
						}
						
						
			  }else{
			     this.$.ti_shi(res.msg);
			  }
			})
			
		},
		groupChanges(n){
			this.radiovalue13=n
		},
		submit(){
				
				this.coupon_price=this.coupon[this.radiovalue13].coupon_price
				this.coupon_title=this.coupon[this.radiovalue13].coupon_title
				this.coupon_id=this.coupon[this.radiovalue13].id
				// console.log(this.coupon_price,this.coupon_title,this.coupon_id)
				this.show=false
				this.couponShow=false
				this.actual_price=Number(this.actual_price)-Number(this.coupon_price)
			
			
		},
        handleChooseFromAddress() {
            this.$.choose_address((res) => {
				 console.log(res)
				this.trailer_address=res.address
				this.trailer_longitude=res.lng
				this.trailer_latitude=res.lat
				
				let k=this.$.calculateDistance(this.lat,this.lng,res.lat,res.lng).toFixed(2)
				// console.log(this.lat,this.lng,res.lat,res.lng,k)
				this.k=Number(k)
				// this.order_price=Number(this.unitPrice)*Number(k)
				// this.actual_price=Number(this.order_price)-Number(this.coupon_price)
            });
        },
        handleChooseToAddress() {
            this.$.choose_address((res) => {
				this.user_location=res.address
				this.user_longitude=res.lng
				this.user_latitude=res.lat
				let k=this.$.calculateDistance(this.lat,this.lng,res.lat,res.lng).toFixed(2)
				this.k=Number(this.k)+Number(k)
				// this.order_price=Number(this.unitPrice)*Number(this.k)
				// this.actual_price=Number(this.order_price)-Number(this.coupon_price)
            });
        },
        buy() {
            unifyOrder(4, { meta: this.formData }).then(({data:{id}}) => {
                this.$u.route('/pages/index/payment',{id})
            });
        },
		// 删除图片
		deletePic(event) {
			this.images.splice(event.index, 1)
			this[`fileList${event.name}`].splice(event.index, 1)
		},
		// 新增图片
		async afterRead(event) {
			// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
			let lists = [].concat(event.file)
			let fileListLen = this[`fileList${event.name}`].length
			lists.map((item) => {
				this[`fileList${event.name}`].push({
					...item,
					status: 'uploading',
					message: '上传中'
				})
			})
			for (let i = 0; i < lists.length; i++) {
				const result = await this.uploadFilePromise(lists[i].url)
				let item = this[`fileList${event.name}`][fileListLen]
				this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
					status: 'success',
					message: '',
					url: result
				}))
				fileListLen++
			}
		},
		uploadFilePromise(url) {
			return new Promise((resolve, reject) => {
				let a = uni.uploadFile({
					url: this.$.ajax_url+'common/upload', // 仅为示例，非真实的接口地址
					filePath: url,
					name: 'file',
					formData: {
						user: 'test'
					},
					success: (res) => {
						this.images.push(JSON.parse(res.data).data.url)
						 // console.log()
						setTimeout(() => {
							resolve(res.data.data)
						}, 1000)
					}
				});
			})
		},
    }
};
</script>

<style scoped lang="scss">
.xcimg {
    width: 140rpx;
    height: 140rpx;
    display: inline-block;
    position: relative;
    margin: 10rpx 9rpx 0;
    .imm_delete {
        position: absolute;
        top: 0;
        right: 0;
        bottom: 0;
        left: 0;
        background: rgba(0, 0, 0, 0.6);
        text-align: center;
        line-height: 140rpx;
        .icon_ljt {
            width: 40rpx;
            height: 40rpx;
        }
    }
}
.box {
    padding: 32rpx;
    .icon_r {
        width: 32rpx;
        height: 32rpx;
        vertical-align: middle;
    }
    .model {
        padding: 32rpx 24rpx;
        border-radius: 24rpx;
        margin-top: 24rpx;
    }
    .carbox {
        width: 100%;
        padding: 24rpx 0;
    }
    .carbox1 {
        width: 100%;
    }
    .inpu {
        width: 70%;
        padding-bottom: 16rpx;
    }
    .carmodel,
    .title {
        width: 30%;
        color: #333a47;
        font-size: 28rpx;
        display: inline-block;
    }
    .car {
        width: 60%;
        color: #ccced1;
        font-size: 28rpx;
        display: inline-block;
    }
    .img_add {
        width: 140rpx;
        height: 140rpx;
        display: inline-block;
        margin-left: 5rpx;
        // margin-top: 15rpx;
    }
    .imgbox {
        background: white;
        border-radius: 24rpx;
        padding: 32rpx 24rpx;
        color: #333a47;
        font-size: 28rpx;
        margin-top: 24rpx;
    }
    .manageLabel {
        width: 30%;
    }
    .nametitle {
        width: 27%;
        font-size: 28rpx;
    }
    .name {
        font-size: 28rpx;
    }
    .tip {
        color: #3377ff;
        font-size: 24rpx;
        margin-top: 24rpx;
    }
}
.button {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    padding: 16rpx 32rpx 50rpx;
    background: #ffffff;
    .buy {
        width: 176rpx;
        height: 76rpx;
        line-height: 76rpx;
        text-align: center;
        color: white;
        border-radius: 8rpx;
        background-image: linear-gradient(to right, #ff924d, #ff6401);
    }
}
.couponBox {
    .discount {
        color: #ff6401;
        font-size: 24rpx;
        text-align: center;
    }
    .title {
        color: #00091a;
        font-size: 32rpx;
        margin-left: 66rpx;
    }
    .time {
        color: #999ca3;
        font-size: 28rpx;
        display: block;
        margin-top: 16rpx;
    }
}
.couponBtn {
    margin: 24rpx auto;
    width: 686rpx;
    height: 100rpx;
    border-radius: 24rpx;
    background: #3377ff;
    text-align: center;
    line-height: 100rpx;
    color: white;
    font-size: 32rpx;
    font-weight: bold;
}
</style>
